import { createApp, ref, watch, App, ComponentPublicInstance } from 'vue';
import { IExpose, Types } from './types.ts';
import Message from './Message.vue';


export default message;

const msgArr = ref<ComponentPublicInstance[]>([]);

function message(txt: string, type: Types, duration: number = 3000) {
    const app = createApp(Message, { txt, type, duration });
    show(app, duration);
}

for (const t of Object.values(Types)) {
    (message as any)[t] = (txt: string, duration: number = 3000) => {
        message(txt, t, duration);
    };
}

function show(app: App, duration: number) {
    const frag = document.createDocumentFragment(),
        vm: ComponentPublicInstance<any> = app.mount(frag);

    msgArr.value.push(vm);
    watch(msgArr, () => setTop(vm));
    document.body.appendChild(frag);

    setTop(vm);
    vm.setVisible(true);
    hide(app, vm, duration);
}

function hide(app: App, vm: ComponentPublicInstance<IExpose>, duration: number) {
    const timer = setTimeout(() => {
        vm.setVisible(false).then(() => {
            app.unmount();
            msgArr.value = msgArr.value.filter((comp) => comp !== vm);
            clearTimeout(timer);
        });
    }, duration);
}

function setTop(vm: ComponentPublicInstance<IExpose>) {
    const { height, margin, setTop } = vm;
    const index = msgArr.value.findIndex((comp) => comp === vm);
    setTop(margin / 2 * (index + 1) + height * index);
}